package com.cls.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cls.business.entity.*;
import com.cls.business.service.*;
import com.cls.business.vo.DeclareTopicVO;
import com.cls.business.vo.TopicSelectVO;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.MyConstant;
import com.cls.common.enums.DictEnum;
import com.cls.common.utils.MyUtil;
import com.cls.common.utils.StringUtils;
import com.cls.system.entity.Configure;
import com.cls.system.entity.Expert;
import com.cls.system.entity.SysDict;
import com.cls.system.entity.User;
import com.cls.system.service.IConfigureService;
import com.cls.system.service.IExpertService;
import com.cls.system.service.ISysDictService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

/**
 * 客户端用户页面跳转
 *
 * @className: ClientViewController.java
 * @description:
 * @author: Carey
 * @createDate 2020/11/9 10:40 上午
 **/
@Controller
@RequiredArgsConstructor
public class ClientViewController extends BaseController {

    private final ISysDictService sysDictService;
    private final IApplicantInfoService applicantInfoService;
    private final ITopicSelectService topicSelectService;
    private final IDeclareTopicService declareTopicService;
    private final INoticeService noticeService;
    private final ITopicService topicService;
    private final IConfigureService configureService;
    private final IExpertService expertService;
    private final ICommitmentService commitmentService;

    /**
     * 客户端首页跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/9 10:42 上午
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "client/index")
    public String pageHome(Model model) {
        // 学科分类
        List<SysDict> subjectTypeCode = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectTypeCode", subjectTypeCode);
        // 审核状态
        List<SysDict> topicStatusCode = sysDictService.findByParentCode(DictEnum.TOPIC_STATUS.getCode());
        model.addAttribute("topicStatusCode", topicStatusCode);
        // 成果形式
        List<SysDict> achievementForm = sysDictService.findByParentCode(DictEnum.ACHIEVEMENT_FORM.getCode());
        model.addAttribute("achievementForm", achievementForm);
        Subject subject = super.getSubject();
        User currentUser = getCurrentUser();
        if (subject.hasRole(MyConstant.REGISTER_ROLE_NAME)) {
            //        用户信息
            ApplicantInfo applicantInfo = applicantInfoService.findByUserId(currentUser.getUserId());
            model.addAttribute("applicantInfo", applicantInfo);
            return MyUtil.view("client/home");
        } else if (subject.hasRole(MyConstant.EXPERT_ROLE_NAME)) {
            // 当前年，课题指南名称列表
            Calendar date = Calendar.getInstance();
            String year = date.get(Calendar.YEAR) + "";
            Topic param = new Topic();
            param.setYear(year);
            List<Topic> topics = topicService.getPublishedTopics(param);
            model.addAttribute("topics", topics);
            Expert expert = expertService.findByUserId(currentUser.getUserId());
            model.addAttribute("expert", expert);
            return MyUtil.view("review/home");
        }
        return MyUtil.view("client/home");
    }

    /**
     * 新增申报页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/addClassApply")
    public String addClassApply(Model model) {
        setApplyDicts(model, DictEnum.ANNUAL);
        User user = getCurrentUser();
        ApplicantInfo applicantInfo = applicantInfoService.findByUserId(user.getUserId());
        model.addAttribute("leader", applicantInfo);
        return MyUtil.view("client/class/apply/addClassApply");
    }

    /**
     * 新增申报页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/addClassEntrust")
    public String addClassEntrust(Model model) {
        setApplyDicts(model, DictEnum.ENTRUST);
        User user = getCurrentUser();
        ApplicantInfo applicantInfo = applicantInfoService.findByUserId(user.getUserId());
        model.addAttribute("leader", applicantInfo);
        return MyUtil.view("client/class/entrust/addEntrustClass");
    }


    /**
     * 修改申报页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/updateEntrustClass/{id}")
    public String updateEntrustClass(Model model, @PathVariable Long id) {
        setUpdateEntrustClass(model, id);
        return MyUtil.view("client/class/entrust/updateEntrustClass");
    }

    /**
     * 修改申报页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/updateEntrustClass/changeApply/{id}")
    public String updateEntrustClassChangeApply(Model model, @PathVariable Long id) {
        setUpdateEntrustClass(model, id);
        model.addAttribute("changeApply", true);
        return MyUtil.view("client/class/entrust/updateEntrustClass");
    }

    private void setUpdateEntrustClass(Model model, Long id) {
        setApplyDicts(model, DictEnum.ENTRUST);
        DeclareTopicVO topicVO = declareTopicService.findByIdVo(id);
        model.addAttribute("result", topicVO);
        model.addAttribute("leader", topicVO.getLeader());
        Topic param = new Topic();
        param.setYear(topicVO.getTopic().getYear());
        List<Topic> topics = topicService.getPublishedTopics(param);
        model.addAttribute("topics", topics);
    }

    /**
     * 修改申报页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/updateClassApply/{id}/{year}")
    public String updateClassApply(Model model, @PathVariable String id, @PathVariable String year) {
        setApplyDicts(model, DictEnum.ANNUAL, year);
        DeclareTopic declareTopic = declareTopicService.getById(id);
        DeclareTopicVO declareTopicVO = new DeclareTopicVO(declareTopic);
        ApplicantInfo leader = applicantInfoService.getById(declareTopic.getApplicantId());
        if (leader != null) {
            declareTopicVO.setLeader(leader);
        }
        List<Configure> configures = configureService.list();
        String businessType = "0";
        if (configures != null && configures.size() == 1) {
            businessType = configures.get(0).getBusinessTypeCode();
            model.addAttribute("businessType", businessType);
        }
        declareTopicVO.setYear(year);
        model.addAttribute("result", declareTopicVO);
        return MyUtil.view("client/class/apply/updateClassApply");
    }

    /**
     * 用户修改页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/updateApplicant")
    public String updateApplicant(Model model) {
        User user = MyUtil.getCurrentUser();
        if (user == null) {
            throw new IllegalArgumentException("未获取当前用户！");
        }

        ApplicantInfo leader = applicantInfoService.findByUserId(user.getUserId());
        model.addAttribute("result", leader);
        setApplyDicts(model, null);
        return MyUtil.view("client/user/updateUser");
    }

    /**
     * 查看申报页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/classApplyDetail/{id}")
    public String classApplyDetail(@PathVariable String id, Model model) {
        DeclareTopic declareTopic = declareTopicService.getById(id);
        DeclareTopicVO declareTopicVO = new DeclareTopicVO(declareTopic);
        ApplicantInfo leader = applicantInfoService.getById(declareTopic.getApplicantId());
        if (leader != null) {
            declareTopicVO.setLeader(leader);
        }
        if (Objects.nonNull(declareTopicVO.getTopicId())) {
            Topic byId = topicService.getById(declareTopicVO.getTopicId());
            declareTopicVO.setTopic(byId);
        }
        String status = declareTopicVO.getStatusTypeCode();
        if (status.equals(DictEnum.PRE_APPLY.getCode())) {
            model.addAttribute("showMore", true);
        }
        model.addAttribute("result", declareTopicVO);
        return MyUtil.view("client/class/apply/classApplyDetail");
    }

    /**
     * 查看委托课题详情页面跳转 entrustClassDetail
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/entrustClassDetail/{id}")
    public String entrustClassDetail(@PathVariable Long id, Model model) {
        setApplyDicts(model, DictEnum.ENTRUST);
        DeclareTopicVO topicVO = declareTopicService.findByIdVo(id);
        model.addAttribute("result", topicVO);
        model.addAttribute("leader", topicVO.getLeader());
        return MyUtil.view("client/class/entrust/entrustClassDetail");
    }

    /**
     * 新增课题页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/addClassSolicit")
    public String addClassSolicit(Model model) {
        setSolicit(model);
        return MyUtil.view("client/class/solicit/addClassSolicit");
    }


    /**
     * 课题修改页面跳转upload-file-prove-a
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/updateClassSolicit/{id}")
    public String updateSolicitDetail(@PathVariable String id, Model model) {
        setSolicit(model);
        TopicSelectVO detail = this.topicSelectService.findTopicDetailForClient(Long.valueOf(id));
        model.addAttribute("result", detail);
        return MyUtil.view("client/class/solicit/updateClassSolicit");
    }

    /**
     * 课题详情页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/classSolicitDetail/{id}")
    public String classSolicitDetail(@PathVariable String id, Model model) {
        setSolicit(model);
        TopicSelectVO detail = this.topicSelectService.findTopicDetailForClient(Long.valueOf(id));
        model.addAttribute("result", detail);
        return MyUtil.view("client/class/solicit/classSolicitDetail");
    }

    /**
     * layout 跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:42 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/layout")
    public String clientLayout() {
        return MyUtil.view("client/layout");
    }


    /**
     * 新增申报页面的新增项目信息
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/addClassApplyProjectInfo")
    public String addClassApplyProjectInfo() {
        return MyUtil.view("client/class/apply/addProjectInfo");
    }


    /**
     * 新增申报页面的新增成员信息
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/addClassApplyMember")
    public String addClassApplyMember(Model model) {
        // 性别
        List<SysDict> sex = sysDictService.findByParentCode(DictEnum.SEX.getCode());
        model.addAttribute("sex", sex);
        // 最终学位 DEGREE
        List<SysDict> degree = sysDictService.findByParentCode(DictEnum.DEGREE.getCode());
        model.addAttribute("degree", degree);
        // 行政职务
        List<SysDict> position = sysDictService.findByParentCode(DictEnum.POSITION.getCode());
        model.addAttribute("positionTypeCode", position);
        // 专业职称
        List<SysDict> title = sysDictService.findByParentCode(DictEnum.TITLE.getCode());
        model.addAttribute("titleTypeCode", title);
        // 证件类型
        List<SysDict> identityTypeCode = sysDictService.findByParentCode(DictEnum.ZJLX.getCode());
        model.addAttribute("identityTypeCode", identityTypeCode);
        return MyUtil.view("client/class/apply/addMember");
    }


    /**
     * 评审结果页面
     * 评审结果页面需要动态列数据
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/classAppraisalResult/{declareTopicId}/{planId}")
    public String classApplyMember(@PathVariable Long declareTopicId, Model model, @PathVariable Long planId) {
        model.addAttribute("planId", planId);
        setBaseAppraisalResult(declareTopicId, model);
        return MyUtil.view("client/class/apply/appraisalResult");
    }

    /**
     * 委托课题评审页面
     * 评审结果页面
     * 评审结果页面需要动态列数据
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/classAppraisalResult/{declareTopicId}")
    public String classApplyEntrustAppraisalResult(@PathVariable Long declareTopicId, Model model) {
        setBaseAppraisalResult(declareTopicId, model);
        return MyUtil.view("client/class/entrust/appraisalResult");
    }

    public void setBaseAppraisalResult(Long declareTopicId, Model model) {
        model.addAttribute("declareTopicId", declareTopicId);
    }


    /**
     * 经费拨付记录页面
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/classAppropriationRecords/{id}")
    public String classAppropriationRecords(@PathVariable String id, Model model) {
        model.addAttribute("id", id);
        return MyUtil.view("client/class/apply/appropriationRecords");
    }


    /**
     * 申请人承诺书页面
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/classApplyCommitment")
    public String classApplyCommitment(Model model) {
        LambdaQueryWrapper<Commitment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Commitment::getIsEnabled, true);
        Commitment one = commitmentService.getOne(wrapper);
        model.addAttribute("commitment", one);
        return MyUtil.view("client/class/apply/classApplyCommitment");
    }

    /**
     * 用户消息页面跳转
     *
     * @return a
     * @author Carey
     * @description
     * @date 2020/11/11 3:43 下午
     */
    @RequestMapping(MyConstant.VIEW_PREFIX + "client/userMessage")
    public String userMessage(String id) {
        return MyUtil.view("client/user/userMessage");
    }

    private void setApplyCommonDict(Model model, DictEnum e) {
        if (null != e) {
            model.addAttribute("classType", e.getCode());
        }
        // 字典表
        // 成果形式
        List<SysDict> achievementForm = sysDictService.findByParentCode(DictEnum.ACHIEVEMENT_FORM.getCode());
        model.addAttribute("achievementForm", achievementForm);
        // 学科分类
        List<SysDict> subjectTypeCode = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectTypeCode", subjectTypeCode);
        // 研究类型
        List<SysDict> research = sysDictService.findByParentCode(DictEnum.RESEARCH.getCode());
        model.addAttribute("research", research);
        // 性别
        List<SysDict> sex = sysDictService.findByParentCode(DictEnum.SEX.getCode());
        model.addAttribute("sex", sex);
        // 行政职务
        List<SysDict> position = sysDictService.findByParentCode(DictEnum.POSITION.getCode());
        model.addAttribute("positionTypeCode", position);
        // 专业职称
        List<SysDict> title = sysDictService.findByParentCode(DictEnum.TITLE.getCode());
        model.addAttribute("titleTypeCode", title);
        // 民族 NATION
        List<SysDict> nation = sysDictService.findByParentCode(DictEnum.NATION.getCode());
        model.addAttribute("nation", nation);
        // 政治面貌 POLITICAL
        List<SysDict> political = sysDictService.findByParentCode(DictEnum.POLITICAL.getCode());
        model.addAttribute("political", political);
        // 外语语种 LANGUAGE
        List<SysDict> language = sysDictService.findByParentCode(DictEnum.LANGUAGE.getCode());
        model.addAttribute("language", language);
        // 最终学位 DEGREE
        List<SysDict> degree = sysDictService.findByParentCode(DictEnum.DEGREE.getCode());
        model.addAttribute("degree", degree);
        // 担任导师
        List<SysDict> tutor = sysDictService.findByParentCode(DictEnum.TUTOR.getCode());
        model.addAttribute("tutor", tutor);
        // 人事关系所在地
        List<SysDict> personnel = sysDictService.findByParentCode(DictEnum.PERSONNEL_AREA.getCode());
        model.addAttribute("personnelAreaType", personnel);

        // 证件类型
        List<SysDict> identityTypeCode = sysDictService.findByParentCode(DictEnum.ZJLX.getCode());
        model.addAttribute("identityTypeCode", identityTypeCode);
        //查询课题分类
        List<Map<String, Object>> group_list = sysDictService.selectByParentCode(DictEnum.TOPIC_LEVEL_TYPE.getCode());
        Map<String, Object> map = new HashMap<>();
        map.put("level", group_list);
        model.addAllAttributes(map);
        List<SysDict> wtktlb = sysDictService.findByParentCode(DictEnum.WTKTLB.getCode());
        model.addAttribute("wtktlb", wtktlb);
    }

    public void setApplyDicts(Model model, DictEnum e, String year) {
        setApplyDicts(model, e);
        // 当前年，课题指南名称列表
        if (StringUtils.isEmpty(year)) {
            Calendar date = Calendar.getInstance();
            year = date.get(Calendar.YEAR) + "";
        }
        Topic param = new Topic();
        param.setYear(year);
        param.setTopicClassifyCode(e.getCode());
        List<Topic> topics = topicService.getPublishedTopics(param);
        model.addAttribute("topics", topics);
    }

    public void setApplyDicts(Model model, DictEnum e) {
        setApplyCommonDict(model, e);

    }


    public void setSolicit(Model model) {
        // 行政职务
        List<SysDict> position = sysDictService.findByParentCode(DictEnum.POSITION.getCode());
        model.addAttribute("positionTypeCode", position);
        // 专业职称
        List<SysDict> title = sysDictService.findByParentCode(DictEnum.TITLE.getCode());
        model.addAttribute("titleTypeCode", title);
        // 成果形式
        List<SysDict> achievementForm = sysDictService.findByParentCode(DictEnum.ACHIEVEMENT_FORM.getCode());
        model.addAttribute("achievementForm", achievementForm);
        // 学科分类
        List<SysDict> subjectTypeCode = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectTypeCode", subjectTypeCode);

        // 征集公告名称
        List<Notice> noticeList = noticeService.findKTZJValidNotices();
        model.addAttribute("noticeList", noticeList);
    }
}
